package com.kun.portal.webframe.controller;

import com.kun.portal.webframe.dao.FwTeamDao;
import com.kun.portal.webframe.dao.GroundServiceSchedulingDao;
import com.kun.portal.webframe.dao.ScheduelItemDao;
import com.kun.portal.webframe.dao.ServiceItemToSelectableUsersDao;
import com.kun.portal.webframe.po.*;
import com.kun.portal.webframe.service.*;
import com.kun.portal.webframe.util.MessageEmit;
import com.kun.portal.webframe.util.MessageFilter;
import com.kun.portal.webframe.util.Status;
import com.kun.portal.webframe.util.UserSessionUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.propertyeditors.CustomDateEditor;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.*;

import javax.persistence.EntityManager;
import javax.servlet.http.HttpSession;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

/**
 * Created by Administrator on 2018/5/10.
 */

@Controller
// /api/flightPlane/saveSchedules

@RequestMapping({"/api/flightPlane"})
public class FlightPlaneController {
    private static final Logger LOG = LoggerFactory.getLogger(FwUserController.class);
    @Autowired
    private FlightPlaneService flightPlaneService;
    @Autowired
    private GroundServiceSchedulingService serviceSchedulingService;
    @Autowired
    private ScheduelItemDao scheduleItem;
    @Autowired
    private GroundServiceItemService groundServiceItemService;
    @Autowired
    private ServiceItemToSelectableUsersDao serviceItemToSelectableUsersDao;
    @Autowired
    private GroundServiceSchedulingDao groundServiceSchedulingDao;
    @Autowired
    private FwTeamDao teamDao;
    @Autowired
    private GpService gpService;
    @Autowired
    private  FlightInfoService flightInfoService;

    @Autowired
    private ProcessMgrService processMgrService;
    @Autowired
    private AppointmentService appointmentService;
    @Autowired
    private  EntityManager entityManager;
    @InitBinder
    public void intDate(WebDataBinder binder){
        DateFormat dateFormat=new SimpleDateFormat("yyyy-MM-dd");
        binder.registerCustomEditor(Date.class, new CustomDateEditor(dateFormat, true));
    }
    @RequestMapping(
            value = {"/save"},
            method = {RequestMethod.POST},
            produces = {"application/json"}
    )
    @ResponseBody
    public FlightPlanePo addOne(@RequestBody FlightPlanePo flightPlanePo){
        flightPlanePo.setPlaneRunStatus(Status.PUBLISHED);
        return flightPlaneService.save(flightPlanePo);
    }

    @RequestMapping(
            value = {"/saveAppointmentAndFlight"},
            method = {RequestMethod.POST},
            produces = {"application/json"}
    )
    @ResponseBody
    public AppointmentPo saveAppointmentAndFlight(@RequestBody AppointmentPo appointmentPo, HttpSession session) {
//        appointmentPo.setUpdateDate(new Date());
        FwUserPo user = UserSessionUtil.getCurrentUser(session);
//        appointmentPo.setUpdatePerson(user);
        return appointmentService.saveAppointmentAndFlightPlane(appointmentPo,user);
    }
    @RequestMapping(
            value = {"/batchSave"},
            method = {RequestMethod.POST},
            produces = {"application/json"}
    )
    @ResponseBody
    public List<FlightPlanePo> batchSave(@RequestBody List<FlightPlanePo> flightPlanePo){
        return flightPlaneService.batchSave(flightPlanePo);
    }


    @RequestMapping(
            value = {"/query"},
            method = {RequestMethod.GET},
            produces = {"application/json"}
    )
    @ResponseBody
    public Page<FlightPlanePo>  query(@RequestParam (required = false) Date startDate ,@RequestParam (required = false) Date endDate ,String flightInfoId, Pageable pageable,HttpSession session){
        return flightPlaneService.query(pageable,startDate,endDate,flightInfoId);
    }
    @RequestMapping(
            value = {"/queryNow"},
            method = {RequestMethod.GET},
            produces = {"application/json"}
    )
    @ResponseBody
    public List<FlightPlanePo> queryNow(@RequestParam (required = false) String flightNum){
        return flightPlaneService.queryNow(flightNum);
    }

    @RequestMapping(
            value = {"/queryScheduling"},
            method = {RequestMethod.GET},
            produces = {"application/json"}
    )
    @ResponseBody
    public Page<GroundServiceFlightPlaneView> queryScheduling(@RequestParam (required = false) String flightInfoId,Date startDate,Date endDate,Boolean scheduled, Pageable page){
        return serviceSchedulingService.query(page,startDate,endDate,flightInfoId,scheduled);

        //return serviceSchedulingService.query(page);
    }
    @RequestMapping(
            value = {"/queryScheded"},
            method = {RequestMethod.GET},
            produces = {"application/json"}
    )
    @ResponseBody
    public List<GroundServiceSchedulings> queryScheded(@RequestParam (required = false) String flightInfoId, Date startDate, Date endDate){
        return serviceSchedulingService.queryScheduled(startDate,endDate,flightInfoId);
        //return serviceSchedulingService.query(page);
    }

    @RequestMapping(
            value = {"/queryAllScheduleItem"},
            method = {RequestMethod.GET},
            produces = {"application/json"}
    )
    @ResponseBody
    public List<GroundServiceItemPo> queryAllSchedulingItem(){
        return groundServiceItemService.findAll();
    }

    @RequestMapping(
            value = {"/deleteScheduleItem"},
            method = {RequestMethod.POST},
            produces = {"application/json"}
    )
    @ResponseBody
    public void deleteSchedulingItem(@RequestBody GroundServiceItemPo groundServiceItemPo){
        scheduleItem.delete(groundServiceItemPo);
    }
    @RequestMapping(
            value = {"/saveScheduleItem"},
            method = {RequestMethod.POST},
            produces = {"application/json"}
    )
    @ResponseBody
    public GroundServiceItemPo saveScheduleItem(@RequestBody GroundServiceItemPo groundServiceItemPo){
//        serviceItemToSelectableUsersDao.save(groundServiceItemPo.getSelectAbleUser());
        return scheduleItem.save(groundServiceItemPo);
    }
    @RequestMapping(
            value = {"/saveScheduleItemTeam"},
            method = {RequestMethod.POST},
            produces = {"application/json"}
    )
    @ResponseBody
    public GroundServiceItemPo saveScheduleItemWithTeam(@RequestBody GroundServiceItemPo groundServiceItemPo){
        //teamDao.save(groundServiceItemPo.getTeams());
        return scheduleItem.save(groundServiceItemPo);
    }
    @RequestMapping(
            value = {"/saveScheduleItemSelectabelUser"},
            method = {RequestMethod.POST},
            produces = {"application/json"}
    )
    @ResponseBody
    @Transactional
    public List <ServiceItemToSelectableUsersPo> saveServiceItemToSelectableUsersPo(@RequestBody List<ServiceItemToSelectableUsersPo> groundServiceItemPo){
        //return scheduleItem.save(groundServiceItemPo);
//        if(groundServiceItemPo.size()>0){
//            ServiceItemToSelectableUsersPo s = groundServiceItemPo.get(0);
//            serviceItemToSelectableUsersDao.deleteAllByGsiId(s.getGsiId());
//        }
        return serviceItemToSelectableUsersDao.save(groundServiceItemPo);
    };
    @RequestMapping(
            value = {"/scheduleOneFlight"},
            method = {RequestMethod.POST},
            produces = {"application/json"}
    )
    @ResponseBody
    @Transactional
    public GroundServiceFlightPlaneView scheduleAuto(@RequestBody(required = false)FlightPlanePo flightPlanePo){
        //return scheduleItem.save(groundServiceItemPo);
        GroundServiceSchedulings gs=  serviceSchedulingService.scheduleAuto(flightPlanePo);
        GroundServiceFlightPlaneView gsv =  new GroundServiceFlightPlaneView(flightPlanePo,gs);
        return gsv;
    };


    @RequestMapping(
            value = {"/scheduleAll"},
            method = {RequestMethod.GET},
            produces = {"application/json"}
    )
    @ResponseBody
    @Transactional
    public String scheduleAll(){
        serviceSchedulingService.scheduleAll();
        return "success";
    };


    @RequestMapping(
            value = {"/saveSchedules"},
            method = {RequestMethod.POST},
            produces = {"application/json"}
    )
    @ResponseBody
    @Transactional
    public GroundServiceSchedulings saveOneSchedule(@RequestBody(required = true)GroundServiceSchedulings schedulings){
        //return scheduleItem.save(groundServiceItemPo);
        return serviceSchedulingService.save(schedulings);
    };

    @RequestMapping(
            value = {"/saveOneSchedule"},
            method = {RequestMethod.POST},
            produces = {"application/json"}
    )
    @ResponseBody
    @Transactional
    public GroundServiceScheduling saveOneSchedule(@RequestBody(required = false)GroundServiceScheduling scheduling){
        //return scheduleItem.save(groundServiceItemPo);
        return groundServiceSchedulingDao.save(scheduling);
    };

    @RequestMapping(
            value = {"/deleteOneSchedule"},
            method = {RequestMethod.POST},
            produces = {"application/json"}
    )
    @ResponseBody
    @Transactional
    public void deleteOneSchedule(@RequestBody(required = false)GroundServiceScheduling scheduling){
//         scheduling.setSelectedUser(null);
//         groundServiceSchedulingDao.save(scheduling);

        groundServiceSchedulingDao.delete(scheduling);
    };


    @RequestMapping(
            value = {"/mySchedule"},
            method = {RequestMethod.GET},
            produces = {"application/json"}
    )
    @ResponseBody
    @Transactional
    public List mySchedule( @RequestParam (required = false) Date startDate, Date endDate, HttpSession session){
        FwUserPo user=UserSessionUtil.getCurrentUser(session);
        return serviceSchedulingService.mySchedule(startDate,endDate,user);
    };

    @RequestMapping(
            value = {"/nodeCompleted"},
            method = {RequestMethod.POST},
            produces = {"application/json"}
    )
    @ResponseBody
    @Transactional
    public CourseNodePo nodeCompleted( @RequestBody (required = false) CourseNodePo courseNodePo, HttpSession session){
        FwUserPo user=UserSessionUtil.getCurrentUser(session);
        courseNodePo.setNodeTime(new Date());
        courseNodePo.setNodeId(null);
        courseNodePo.setDataEntryClerk(user);
        return processMgrService.nodeCompleted(courseNodePo);
    };


    @RequestMapping(
            value = {"/queryScheduleToday"},
            method = {RequestMethod.GET},
            produces = {"application/json"}
    )
    @ResponseBody
    @Transactional
    public List queryScheduleToday( @RequestParam (required = false) Integer beforeHour, Integer afterHour, HttpSession session){
        FwUserPo user=UserSessionUtil.getCurrentUser(session);
        return  serviceSchedulingService.queryScheduleToday(beforeHour,afterHour);
    };


    @RequestMapping(
            value = {"/schedulingReceive"},
            method = {RequestMethod.POST},
            produces = {"application/json"}
    )
    @ResponseBody
    @Transactional
    public GroundServiceScheduling schedulingReceive( @RequestBody GroundServiceScheduling g, HttpSession session){
        g.setStartDate(new Date());
        g.setStatus("任务开始");
        return groundServiceSchedulingDao.save(g);
    };

    @RequestMapping(
            value = {"/schedulingFinish"},
            method = {RequestMethod.POST},
            produces = {"application/json"}
    )

    @ResponseBody
    @Transactional
    public GroundServiceScheduling schedulingFinish( @RequestBody GroundServiceScheduling g, HttpSession session){
        g.setEndDate(new Date());
        g.setStatus("任务结束");
        return groundServiceSchedulingDao.save(g);
    };
    @RequestMapping(
            value = {"/findInterimFlightPlane"},
            method = {RequestMethod.GET},
            produces = {"application/json"}
    )
    @ResponseBody
    public Page<FlightPlanePo> findInterimFlightPlane(@RequestParam(required = false) String planeProperty ,@RequestParam(required = false) Date exceptDate,
                                                      @RequestParam(required = false)  Date estimatedTime, String importOrExport,  Pageable pageable, HttpSession session) {
        return flightPlaneService.queryInterimPlane(pageable,planeProperty,exceptDate,estimatedTime,importOrExport);
    }




    @RequestMapping(
            value = {"/findInterimFlightPlaneNoPage"},
            method = {RequestMethod.GET},
            produces = {"application/json"}
    )
    @ResponseBody
    public List<FlightPlanePo> findInterimFlightPlaneNoPage(@RequestParam(required = false) String planeProperty ,@RequestParam(required = false)String flightInfoId, @RequestParam(required = false) Date exceptDateS,
                                                            @RequestParam(required = false) Date exceptDateE,
                                                            @RequestParam(required = false)  Date estimatedTimeS,@RequestParam(required = false)  Date estimatedTimeE, String importOrExport,  String order, HttpSession session) {
        return flightPlaneService.queryInterimPlaneNoPage(order,flightInfoId,planeProperty,exceptDateS,exceptDateE,estimatedTimeS,estimatedTimeE,importOrExport);
    }

    @RequestMapping(
            value = {"/findAppointmentFlightPlaneNoPage"},
            method = {RequestMethod.GET},
            produces = {"application/json"}
    )
    @ResponseBody
    public List<FlightPlanePo> findAppointmentFlightPlaneNoPage(@RequestParam(required = false) String planeProperty ,@RequestParam(required = false)String flightInfoId, @RequestParam(required = false) Date exceptDateS,
                                                                @RequestParam(required = false) Date exceptDateE,
                                                                @RequestParam(required = false)  Date estimatedTimeS,@RequestParam(required = false)  Date estimatedTimeE, String importOrExport,  String order, HttpSession session) {
        return flightPlaneService.queryAppointmentPlaneNoPage(order,flightInfoId,planeProperty,exceptDateS,exceptDateE,estimatedTimeS,estimatedTimeE,importOrExport);
    }
    @RequestMapping(
            value = {"/findNextDayPlan"},
            method = {RequestMethod.GET},
            produces = {"application/json"}
    )
    @ResponseBody
    public List<FlightPlanePo> findNextDayPlane(@RequestParam(required = false)String flightInfoId, @RequestParam(required = false) Date estimatedTime,
                                                String importOrExport,  String order, HttpSession session) {
        return flightPlaneService.queryNextPlane(order,flightInfoId,estimatedTime,importOrExport);
    }


    @RequestMapping(
            value = {"/findTodayPlane"},
            method = {RequestMethod.GET},
            produces = {"application/json"}
    )
    @ResponseBody
    public List<FlightPlanePo> findTodayPlane(@RequestParam(required = false)String flightInfoId, @RequestParam(required = false) Date estimatedTime,
                                              String importOrExport,  String order, HttpSession session) {
        return flightPlaneService.queryTodayPlaneWidthNode(order,flightInfoId,estimatedTime,importOrExport);
    }


    @RequestMapping(
            value = {"/findFlightDynamicPlaneNoPage"},
            method = {RequestMethod.GET},
            produces = {"application/json"}
    )
    @ResponseBody
    public List<FlightPlanePo> findFlightDynamicPlaneNoPage(@RequestParam(required = false) Boolean all, Boolean export,Boolean isImport,
                                                            Boolean normal,
                                                            Boolean abnormal,
                                                            Boolean overtime,   String flightNum,  String order, HttpSession session) {
        return flightPlaneService.findFlightDynamicPlaneNoPage(all,export,isImport,normal,abnormal,overtime,flightNum,order);
    }
    /*到达近空*/
    @RequestMapping(
            value = {"/arriveNearSpace"},
            method = {RequestMethod.POST},
            produces = {"application/json"}
    )
    @ResponseBody

    public FlightPlanePo arriveNearSpace(@RequestParam(required = false) String planeId,@RequestParam(required = false) String inOrOut){
        FlightPlanePo flightPlanePo = flightPlaneService.findOneById(planeId);
        if("出港".equals(inOrOut)){
            flightPlanePo.setProcessStatus(Status.OUTSIDE_NEAR_SPACE);
        }
        if("进港".equals(inOrOut)){
            flightPlanePo.setProcessStatus(Status.NEAR_SPACE);
        }
       return  flightPlaneService.save(flightPlanePo);
    }
    /*飞机着落*/
    @RequestMapping(
            value = {"/landing"},
            method = {RequestMethod.POST},
            produces = {"application/json"}
    )
    @ResponseBody
    public FlightPlanePo landing(@RequestParam(required = false) String planeId,@RequestParam(required = false) String inOrOut){
        FlightPlanePo flightPlanePo = flightPlaneService.findOneById(planeId);
        if("出港".equals(inOrOut)){
            flightPlanePo.setProcessStatus(Status.OUTSIDE_LANDED);
        }
        if("进港".equals(inOrOut)){
            flightPlanePo.setProcessStatus(Status.LANDED);
            GpConfigPo gpConfigPo =flightPlanePo.getGpConfigPo();

            if(gpConfigPo!=null&&(gpConfigPo.getRunStatus()==Status.AerodromeStatus.ALLOCATED_UN_OCCUPY||gpConfigPo.getRunStatus()==Status.AerodromeStatus.FREE)){
                 /*如果已分配机位则机位占用,如果未分配则跳过*/
                gpConfigPo.setCurrentFlight(flightPlanePo.getFlightInfo());
                gpConfigPo.setRunStatus(Status.AerodromeStatus.OCCUPY);
                gpService.saveGp(gpConfigPo);
            }
        }
        flightPlanePo.setRealArriveTime(new Date());
       return flightPlaneService.save(flightPlanePo);
    }
    /*飞机准备起飞*/
    @RequestMapping(
            value = {"/expectedToFlylanding"},
            method = {RequestMethod.POST},
            produces = {"application/json"}
    )
    @ResponseBody
    @Transactional
    public FlightPlanePo expectedToFlylanding(@RequestParam(required = false) String planeId,@RequestParam(required = false) String inOrOut){

        FlightPlanePo flightPlanePo = flightPlaneService.findOneById(planeId);
        if("出港".equals(inOrOut)){
            flightPlanePo.setProcessStatus(Status.EXPECTED_TO_FLY);
        }
        if("进港".equals(inOrOut)){
            flightPlanePo.setProcessStatus(Status.OUTSIDE_EXPECTED_TO_FLY);
        }

        flightPlanePo.getCourseNodePos();
        MessageEmit.emit(flightPlanePo, MessageFilter.MessageType.processStatusChange);

       return flightPlaneService.save(flightPlanePo);
    }
/*飞机起飞*/
    @RequestMapping(
            value = {"/takeOff"},
            method = {RequestMethod.POST},
            produces = {"application/json"}
    )
    @ResponseBody
    public FlightPlanePo takeOff(@RequestParam(required = false) String planeId,@RequestParam(required = false) String inOrOut){
        FlightPlanePo flightPlanePo = flightPlaneService.findOneById(planeId);
        if("出港".equals(inOrOut)){
            flightPlanePo.setProcessStatus(Status.TAKE_OFF);
            /*停机位设置为未占用未分配*/
            GpConfigPo gpConfigPo= flightPlanePo.getGpConfigPo();
            if(gpConfigPo!=null){
                gpConfigPo.setRunStatus(Status.AerodromeStatus.FREE);
                gpConfigPo.setCurrentFlight(null);
                gpService.saveGp(gpConfigPo);
            }
        }
        if("进港".equals(inOrOut)){
            flightPlanePo.setProcessStatus(Status.OUTSIDE_TAKE_OFF);
        }
        flightPlanePo.setRealFlyTime(new Date());
        flightPlanePo.getCourseNodePos();
        MessageEmit.emit(flightPlanePo, MessageFilter.MessageType.processStatusChange);

       return flightPlaneService.save(flightPlanePo);
    }
    /*预计落地航班*/
    @RequestMapping(
            value = {"/expectedToFall"},
            method = {RequestMethod.POST},
            produces = {"application/json"}
    )
    @ResponseBody
    @Transactional
    public FlightPlanePo expectedToFall(@RequestParam(required = false) String planeId,@RequestParam(required = false) String inOrOut){
        FlightPlanePo flightPlanePo = flightPlaneService.findOneById(planeId);
        if("出港".equals(inOrOut)){
            flightPlanePo.setProcessStatus(Status.OUTSIDE_EXPECTED_TO_FALL);
        }
        if("进港".equals(inOrOut)){
            flightPlanePo.setProcessStatus(Status.EXPECTED_TO_FALL);
            GpConfigPo gpConfigPo =flightPlanePo.getGpConfigPo();
            if(gpConfigPo!=null&&gpConfigPo.getRunStatus()==Status.AerodromeStatus.FREE){
                 /*如果已分配机位则机位占用,如果未分配则跳过*/
                FlightInfoPo flightInfoPo = flightPlanePo.getFlightInfo();
                flightInfoPo.setGpConfigPo(gpConfigPo);
                flightInfoService.saveFlightInfo(flightInfoPo);
                gpConfigPo.setRunStatus(Status.AerodromeStatus.ALLOCATED_UN_OCCUPY);
                gpService.saveGp(gpConfigPo);

            }
        }
        GpConfigPo gpConfigPo =flightPlanePo.getGpConfigPo();
        flightPlanePo = flightPlaneService.save(flightPlanePo);
        flightPlanePo.setGpConfigPo(gpConfigPo);
        flightPlanePo.getCourseNodePos();
        MessageEmit.emit(flightPlanePo, MessageFilter.MessageType.processStatusChange);

       return flightPlanePo;
    }
    /*确定为延误航班*/
    @RequestMapping(
            value = {"/confirmDelay"},
            method = {RequestMethod.POST},
            produces = {"application/json"}
    )
    @ResponseBody
    public FlightPlanePo confirmDelay(@RequestParam(required = false) String planeId,@RequestParam(required = false) String delayReason){
        FlightPlanePo flightPlanePo = flightPlaneService.findOneById(planeId);
        flightPlanePo.setIsDelay("延误");
        flightPlanePo.setDelayReason(delayReason);
        flightPlanePo.getCourseNodePos();
        MessageEmit.emit(flightPlanePo, MessageFilter.MessageType.processStatusChange);

        return flightPlaneService.save(flightPlanePo);
    }
    /*分配机位*/
    @RequestMapping(
            value = {"/gpa"},
            method = {RequestMethod.POST},
            produces = {"application/json"}
    )
    @ResponseBody
    public FlightPlanePo confirmGpa(@RequestParam(required = false) String planeId,
                                    @RequestParam(required = false) String gpId){
        FlightPlanePo flightPlanePo = flightPlaneService.findOneById(planeId);
       // entityManager.merge(flightPlanePo);
        GpConfigPo gpConfigPo=gpService.findByOne(gpId);
        if(flightPlanePo.getProcessStatus()>=Status.LANDED){//分配机位时飞机已着陆
            GpConfigPo gpConfigPo2 =  flightPlanePo.getFlightInfo().getGpConfigPo();
            gpConfigPo2.setRunStatus(Status.AerodromeStatus.FREE);
            gpConfigPo2.setCurrentFlight(null);
            gpService.saveGp(gpConfigPo2);
            gpConfigPo.setRunStatus(Status.AerodromeStatus.OCCUPY);
            gpConfigPo.setCurrentFlight(flightPlanePo.getFlightInfo());
            GpConfigPo gpConfigPo1=gpService.saveGp(gpConfigPo);
            flightPlanePo.setGpConfigPo(gpConfigPo1);
        }else{ //分配机位时飞机未着陆
            GpConfigPo gpConfigPo1= gpService.saveGp(gpConfigPo);
            flightPlanePo.setGpConfigPo(gpConfigPo1);
        }
        gpConfigPo = flightPlanePo.getGpConfigPo();
        flightPlanePo = flightPlaneService.save(flightPlanePo);
        flightPlanePo.setGpConfigPo(gpConfigPo);
        return flightPlanePo;
    }
    @RequestMapping(
            value = {"/findFlightDynamicPlaneToday"},
            method = {RequestMethod.GET},
            produces = {"application/json"}
    )
    @ResponseBody
    public List<FlightPlanePo>findFlightDynamicPlaneToday(@RequestParam(required = false) Date estimatedTime,
                                                          @RequestParam(required = false) String flightNum,
                                                          @RequestParam(required = false)String importOrExport,
                                                          String order
    ) {
        return flightPlaneService.findFlightDynamicPlaneToday(estimatedTime,flightNum,importOrExport,order);
    }


}








